<template>
  <div class="login-background">
    <div class="login-background-containers">
      <div class="login-main main-container-content">
        <div class="login-content">
          <el-row :gutter="0" type="flex" justify="center" class="rowflex">
            <el-col :xs="20" :sm="10" :md="8" :lg="6" :xl="6">
              <div class="left-content">
                <!-- <div class="bg"></div> -->
                <div class="cont">
                  <div>
                    <div class="login-platformName">
                    <!-- <img :src="systemLogoUrl" class="login-logo" alt="系统LOGO" /> -->
                    <!-- http://www.aikeji.top:50005/_uploads/PHOTO/1722578117626.png -->
                    长海医院
                  </div>
                  <div class="left-title public-padding">病理学线上教学系统</div>
                  <img src="@/assets/images/leftImg.png" class="login-platImg" alt="" />
                
                  </div>
              
                  <!-- <div class="login-platformName-company">上海爱可及医疗科技有限公司 <br />提供技术支持</div> -->
                </div>
              </div>
            </el-col>
            <el-col :xs="20" :sm="2" :md="2" :lg="2" :xl="2"></el-col>
            <el-col :xs="20" :sm="12" :md="10" :lg="8" :xl="8">
              <div class="right-content">
                <!-- tabs -->
                <div class="login-tabs">
                  <div class="login-tabs-item " :class="loginType == 1 ? 'active' : ''" @click="changeLogin(1)">
                    登 录
                  </div>
                  <div class="login-tabs-item" :class="loginType == 0 ? 'active' : ''" @click="changeLogin(0)">
                    注 册
                  </div>
                </div>
                <el-form>
                  <el-row class="login-row" type="flex" justify="center">
                    <el-col>
                      <el-input class="longin-public" v-model="username" placeholder="请输入用户名"
                        prefix-icon="el-icon-user" />
                    </el-col>
                  </el-row>
                  <el-row class="login-row" type="flex" justify="center">
                    <el-col>
                      <el-input class="longin-public" placeholder="请输入密码" @keyup.13.native="userLogin" v-model="password"
                        prefix-icon="el-icon-lock" show-password />
                    </el-col>
                  </el-row>
                </el-form>
                <div class="login-rememberMe">
                  <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
                  <div class="login-rememberMe-text">忘记密码？</div>
                </div>
                <el-row class="login-row">
                  <el-col type="flex" justify="center">
                    <el-button :loading="isLoading" @click="userLogin" class="longin-public login-button">
                      登 录
                    </el-button>
                  </el-col>
                </el-row>
                <!-- <div class="login-platformName-company-right">
                  上海爱可及医疗科技有限公司 <br />提供技术支持
                </div> -->
              </div>
            </el-col>
          </el-row>
        </div>


      </div>
    </div>
      <!--  底部  -->
      <div class="el-login-footer">
      <span>Copyright © 上海爱可及医疗科技有限公司技术支持</span>
    </div>
    <el-dialog :visible.sync="isResetVisible" :title="resetMessage" :close-on-click-modal="false"
      :modal-append-to-body="false" append-to-body :width="device === 'mobile' ? '90%' : '40%'">
      <el-form label-width="80px" :model="resetForm" :rules="resetRule" ref="resetForm" @submit.native.prevent>
        <el-row class="reset-row">
          <el-col :span="24">
            <el-form-item label="身份证号" prop="pCardId">
              <el-input placeholder="身份证号后四位" v-model="resetForm.pCardId" @keyup.enter.native="loginResetset" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-button class="login-button longin-reset" @click="loginResetset"
              :loading="isResetLoading">用户重置并登录</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <div class="registerDailog" v-if="registerDailog">
      <registration @close="closedDailog"></registration>
    </div>
  </div>
</template>

<script>
import moment from 'moment/moment';
import VueSeamlessScroll from 'vue-seamless-scroll';
import registration from '@/components/common/registration/index'
export default {
  name: 'Login',
  components: {
    VueSeamlessScroll,
    registration
  },
  data() {
    const checkNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'));
      }
      // const reg =
      //     /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      // if (reg.test(value)) {
      //     return callback();
      // }
      return callback();
    };
    return {
       // 系统logo地址
       systemLogoUrl: 'http://www.aikeji.top:50005/_uploads/PHOTO/1722578117626.png',
      loginType: 1,
      rememberMe:'',
      registerDailog: false,
      noticeDialogVisible: false,
      notice: {},
      isResetVisible: false,
      resetForm: { pCardId: '' },
      resetRule: {
        pCardId: [
          // 身份证号码
          {
            type: 'number',
            validator: checkNumber,
            message: `请输入身份证号`,
            trigger: 'blur',
          },
        ],
      },
      isResetLoading: false,
      resetMessage:
        '帐号已经登录!请输入身份证号后四位重置,若重置失败,请联系管理员!',
      username: '',
      password: '',
      platformName: '',
      abbreviation: '',
      // systemLogoUrl: '/images/logo-now.png',
      passwordStrength: false,
      notices: [],
      scrollClassOption: {
        // 轮播鼠标控制停止
        hoverStop: true,
        // 轮播速度
        step: 0.4,
        // 开始无缝滚动最小数据长度
        limitMoveNum: 1,
        direction: 1, // 0 往下 1 往上 2向左 3向右
        switchDisabledClass: 'NO',
      },
      isShowFrontPage: false,
      isLoading: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  computed: {
    device() {
      return this.$store.state.device
    }

  },
  methods: {
    closedDailog() {
      this.registerDailog = false
      this.loginType = 1
      this.canScroll()
    },
    changeLogin(type) {
      this.loginType = type
      if (type == 0) {
        this.registerDailog = true
        this.stopScroll()
      } else {
        this.registerDailog = false
      }
    },
    async getPlatform() {
      try {
        await this.$axios({
          // 详见 axios 请求配置项
          method: 'GET',
          url: '/institutions/platform',
        }).then((res) => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data);
          }
          // 请求成功
          const result = res.data.data;
          this.platformName = '长海医院'//result.name;


        });
      } catch (e) {
        // 跳出
      }
    },

    async userLogin() {
      // 使用 try catch模式
      try {
        this.isLoading = true;
        let Base64 = require('js-base64').Base64;
        let _this = this;
        await this.$axios({
          method: 'POST',
          url: '/login',
          params: {
            username: this.username,
            password: Base64.encode(this.password),
          },
        }).then((res) => {
          this.isLoading = false;
          // 请求失败
          if (res.data.code !== 200) {
            const message = res.data.message;
            if (res.data.code === 500 && !res.data.data) {
              if (message === '此账号不存在') {
                _this.$message.warning(message);
              } else if (message === '此账号已被冻结') {
                _this.$message.warning(message);
              } else if (message === '此账号已被删除') {
                _this.$message.warning(message);
              } else {
                this.isResetVisible = true;
              }
              return;
            }

            _this.$message.warning(message);

            return;
          }
          // 请求成功
          const result = res.data.data;

          const platform = {
            name: '浦东医院病理平台',
          };
          let roleIds = [];
          if (result.userInfo.roles) {
            result.userInfo.roles.forEach((item) => {
              roleIds.push(item.id);
            });
          }

          const user = {
            id: result.userInfo.id,
            name: result.userInfo.name,
            headImgUrl: result.userInfo.headUrl,
            isDivisionConsultationApplyPermissions:
              result.userInfo
                .isDivisionConsultationApplyPermissions, //科内会诊申请权限
            isOutsideConsultationApplyPermissions:
              result.userInfo
                .isOutsideConsultationApplyPermissions, //院外会诊申请权限
            roleIds,
          };
          const permissionList = result['ui-item'];
          console.log('permissionList-before', permissionList);
          for (let init = 0; init < permissionList.length; init++) {
            for (
              let i = 0;
              i < permissionList[init].permissionList.length;
              i++
            ) {
              const iconString =
                permissionList[init].permissionList[i].icon;
              const [prefix, icon] = _.split(iconString, ' ');
              permissionList[init].permissionList[i].prefix =
                prefix;
              permissionList[init].permissionList[i].icon = icon;
            }
          }
          // 存储缓存数据
          this.$store.commit('setPlatform', platform);
          this.$store.commit('setPermissionList', permissionList);
          this.$store.commit('loginTimeFlash');
          //设置是否全屏
          this.$store.commit('fullScreenChange', true);
          // 设置登陆后的跳转页
          this.$store.commit('setPropertyGeneral', {
            key: 'nowRoute',
            value: permissionList[0].permissionList[0].route,
          });
          this.$store.commit('setUser', user);
          console.log(this.redirect)
          this.$router.push({ path: this.redirect ? this.redirect : "/index" }).catch(() => { });
          // this.$router.push({
          //   path: '/index',
          // });

          //   this.$axios({
          //     method: 'GET',
          //     url: `/institutions/${result.userInfo.institutionId}`,
          //   }).then((res2) => {
          //     console.log(res2);
          //     if (res2 && res2.data.code === 200) {
          //       const info = res2.data.data;
          //       const institution = {
          //         id: info.id,
          //         isPlatform: info.isPlatform,
          //         name: info.name,
          //         isEnableTaskClaim: info.isEnableTaskClaim,
          //       };
          //       this.$store.commit('setInstitution', institution);
          //     }
          //   });
        });
      } catch (e) {
        if (isPromptLoginMessage(e.message, 'LOGIN')) {
          this.$message.error(e.message);
        }
      }
    },
    async loginResetset() {
      console.log('1---------------------------------');
      let isValidate = false;
      this.$refs.resetForm.validate((valid) => {
        if (valid) {
          isValidate = true;
        }
      });
      if (!isValidate) {
        return;
      }
      this.isResetLoading = true;
      await this.$axios({
        // 详见 axios 请求配置项
        method: 'GET',
        url: `/login/reset/token/card/id/${this.username}/${this.resetForm.pCardId}`,
      }).then((res) => {
        this.resetCount += 1;
        this.isResetVisible = false;
        // 请求失败
        if (res.data.code !== 200 || !res.data.data) {
          const message = '重置登录失败，请联系管理员重置！！！';
          if (isPromptLoginMessage(message, 'LOGIN')) {
            this.$message.warning({ message });
          }
          return;
        }
        this.userLogin();
      });
      this.resetForm.pCardId = '';
      this.isResetLoading = false;
    },
  },
  mounted() {
    this.getPlatform()
    this.$store.commit('stateInit');

  },
};
</script>

<style scoped lang="scss">
 .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 10px;
    width: 100%;
    text-align: center;
    color: rgba(44,43,43,0.5);
    font-size:14px;
    letter-spacing: 1px;
  }
.login-rememberMe{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top:6px;
  .login-rememberMe-text{
    font-size:14px;
    color:rgba(44,43,43,0.5);
    cursor: pointer;
  }
}
.login-background {
  width: 100%;
  height: 100%;
  background-image: url('../assets/images/bj.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}
.login-platImg{
  margin-top:20px;
  width:95%;
}
.login-background-containers {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.left-content {
  position: relative;
  width: 100%;
  height: 408px;
}

.bg {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #3a62d7;
  opacity: 0.5;
}

.rowflex {
  flex-wrap: wrap;
}

.cont {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-content {
  height: 408px;
  box-sizing: border-box;
  padding:20px 40px;
  background-color: #ffffff;
  border-radius: 8px;
  /* background-image: url('/images/login-pic.png'); */
}
.login-logo{
   height:80px;
}

.login-platformName {
  color: #3a62d7;
  font-size: 16px;
  font-weight: 500;
  text-align: center;
  /* padding: 60px 0; */
  padding-bottom:5px;
}

.left-title {
  display: block;
  font-size: 24px;
  font-family: 'Microsoft YaHei', serif;
  font-weight: 500;
  text-align: center;
  color: #3a62d7;
  line-height: 40px;
}

.login-platformName-company {
  text-align: center;
  color: #ffffff;
  margin-top: 140px;
  display: block;
}

.login-platformName-company-right {
  text-align: center;
  margin-top: 30px;
  display: none;
}

.login-tabs {
  display: flex;
  align-items: center;
  justify-content: center;

}

.login-tabs-item {
  width: 50%;
  height: 50px;
  line-height: 50px;
  font-size: 16px;
  text-align: center;
  cursor: pointer;
  border-bottom: 1px solid #ddd;
}

.login-tabs-item.active {
  color: #3a62d7;
  border-bottom: 1px solid #3a62d7;
}

.login-row {
  margin-top: 30px;
}

.login-row .el-input__inner,
.login-row .longin-public {
  border-radius: 46px;
  min-height:46px;
  width: 100%;
  height: 46px;
}

.reset-row .longin-reset {
  margin-top: 12px;
  border-radius: 15px;
  min-height: 38px;
  width: 100%;
  height: 38px;
}

.login-button {
  background-color: #3a62d7;
  color: white;
  border: 1px solid #3a62d7;
   margin-top:20px; 
}
</style>
